package danny.hoi.web.controller.pdf;

import com.alibaba.dubbo.config.annotation.Reference;
import danny.hoi.domain.export.cargo.*;
import danny.hoi.service.cargo.ContractService;
import danny.hoi.service.cargo.ExportProductService;
import danny.hoi.service.cargo.ExportService;
import danny.hoi.service.cargo.FactoryService;
import danny.hoi.web.controller.base.BaseController;
import danny.hoi.web.utils.BeanMapUtils;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/export")
public class PdfController extends BaseController {
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;
    @Reference
    private ContractService contractService;
    @Reference
    private FactoryService factoryService;

    /**
     * 打印电子报运单
     * 请求地址:/cargo/export/exportPdf.do?id=${o.id}
     *
     * @param id 报运单id
     *           响应地址:异步响应,下载pdf
     */
    @RequestMapping("/exportPdf")
    @ResponseBody
    public void exportPdf(String id) {
        //1.获取pdf模板输入流
        InputStream in =
                session.getServletContext().getResourceAsStream("/pdf/export.jasper");
        //2.1 根据报运单id查询报运单
        Export export = exportService.findById(id);
        //2.2 将报运单对象封装成map集合
        Map<String, Object> map = BeanMapUtils.beanToMap(export);
        //3.1 根据报运单id获取报运商品列表
        ExportProductExample epExample = new ExportProductExample();
        epExample.createCriteria()
                .andExportIdEqualTo(id)
                .andCompanyIdEqualTo(getLoginCompanyId());
        List<ExportProduct> list = exportProductService.findAll(epExample);
        //3.2根据工厂id查询工程名字
        if (list != null && list.size() > 0) {
            for (ExportProduct exportProduct : list) {
                Factory factory = factoryService.findById(exportProduct.getFactoryId());
                exportProduct.setFactoryName(factory.getFactoryName());
            }
        }

        //3.2封装jr数据源
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
        OutputStream out = null;
        try {
            //4 封装jsaperPrint
            JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, dataSource);
            //5 输出pdf
            //5.1获取响应输出流
            out = response.getOutputStream();
            //5.2设置响应头
            response.setHeader("content-disposition", "attachment;filename=export.pdf");
            response.setContentType("application/pdf;charset=utf-8");
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        release(in, out);
    }

    /**
     * 打印合同
     * 请求地址:    /cargo/export/downLoadContract.do?id="+id;
     * 下载合同pdf
     */
    @RequestMapping("/downLoadContract")
    @ResponseBody
    public void downLoadContract(String id) {
        //1.获取合同模板
        InputStream in =
                session.getServletContext().getResourceAsStream("/pdf/contract.jasper");
        //2.1 根据购销合同id查询合同
        Contract contract = contractService.findById(id);
        //2.2 封装jasper参数map集合
        Map<String, Object> map = BeanMapUtils.beanToMap(contract);

        OutputStream out = null;
        try {
            //3 填充模板数据
            JasperPrint print = JasperFillManager.fillReport(in, map, new JREmptyDataSource());
            //4.1 获取响应输出流
            out = response.getOutputStream();
            //4.2 设置响应头
            response.setHeader("content-disposition", "attachment;filename=contract.pdf");
            response.setContentType("application/pdf;charset=utf-8");
            //5 输出pdf
            JasperExportManager.exportReportToPdfStream(print, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //6 释放资源
        release(in, out);
    }


    /**
     * 释放输入/输出资源
     */
    private void release(InputStream in, OutputStream out) {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
